package com.snowj.apaas.web;

import com.snowj.apaas.domain.auto.Users;
import com.snowj.apaas.service.UsersService;
import com.snowj.apaas.service.utils.PaginationUtil;
import com.snowj.apaas.service.utils.ResponseUtil;
import com.snowj.apaas.web.vm.UsersVm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * @author oliver
 * @date 2020/9/26
 */
@Api(value = "用户管理", tags = {"用户操作接口"})
@RestController
@RequestMapping("/api")
public class UsersController {

    private final UsersService usersService;

    public UsersController(UsersService usersService) {
        this.usersService = usersService;
    }

    /**
     * 获取用户列表
     * @param pageable 分页信息
     * @return 用户列表
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/users")
    public ResponseEntity<List<UsersVm>> listUsers(Pageable pageable) {
        Page<UsersVm> page = usersService.listUsers(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page);
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }


    /**
     * 获取用户信息
     *
     * @param username
     * @return
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/users/{username}")
    public ResponseEntity<UsersVm> getUserByUsername(@PathVariable String username) {
        Optional<UsersVm> usersOptional = usersService.getUserByUsername(username);
        return ResponseUtil.wrapOrNotFound(usersOptional);
    }


    /**
     * 创建用户
     *
     * @param users
     * @return
     */
    @ApiOperation("新增用户")
    @PostMapping("/users")
    public ResponseEntity<Users> createUser(@RequestBody UsersVm users) {
        Users user = usersService.createUser(users);
        return ResponseEntity.ok(user);
    }


    /**
     * 编辑用户
     *
     * @param users
     * @return
     */
    @ApiOperation("编辑用户")
    @PutMapping("/users")
    public ResponseEntity<Users> updateUser(@RequestBody UsersVm users) {
        Users user = usersService.updateUser(users);
        return ResponseEntity.ok(user);
    }

    /**
     * 删除用户
     * @param username
     */
    @ApiOperation("删除用户")
    @DeleteMapping("/users/{username}")
    public ResponseEntity<Void> deleteUser(@PathVariable String username) {
        usersService.deleteUser(username);
        return ResponseEntity.noContent().build();
    }
}

